package com.jf.cloud.service.sysmanager.common.util;

import org.springframework.util.Assert;

/**
 * 恺撒密码 简单散列加密 
 * @author ouyang 创建时间：May 5, 2012 1:12:33 PM
 */
public class Crypter
{
	private static final char[] UC_ENCRYPT_CHARS = { 'L', 'D', 'X', 'U', 'H', 'I', 'B', 'E', 'J', 'C', 'T', 'N', 
		'K', 'O', 'G', 'W', 'R', 'S', 'F', 'Y', 'V', 'M', 'Z', 'Q', 'A', 'P' };

	private static final char[] LC_ENCRYPT_CHARS = { 'l', 'd', 'x', 'u', 'h', 'i', 'b', 'e', 'j', 'c', 't', 'n', 
		'k', 'o', 'g', 'w', 'r', 's', 'f', 'y', 'v', 'm', 'z', 'q', 'a', 'p' };

	private static char[] UC_DECRYPT_CHARS = new char[26]; // 大写

	private static char[] LC_DECRYPT_CHARS = new char[26]; // 小写

	static {
		for (int i = 0; i < 26; i++) {
			char b = UC_ENCRYPT_CHARS[i];
			UC_DECRYPT_CHARS[b - 'A'] = (char) ('A' + i);

			b = LC_ENCRYPT_CHARS[i];
			LC_DECRYPT_CHARS[b - 'a'] = (char) ('a' + i);
		}
	}

   static char encrypt(char b) {
		if (b >= 'A' && b <= 'Z') {
			return UC_ENCRYPT_CHARS[b - 'A'];
		} else if (b >= 'a' && b <= 'z') {
			return LC_ENCRYPT_CHARS[b - 'a'];
		} else {
			return b;
		}
	}

  static char decrypt(char b) {
		if (b >= 'A' && b <= 'Z') {
			return UC_DECRYPT_CHARS[b - 'A'];
		} else if (b >= 'a' && b <= 'z') {
			return LC_DECRYPT_CHARS[b - 'a'];
		} else {
			return b;
		}
	}
	/**
	 * 加密
	 * @author ouyang 创建时间：May 5, 2012 1:15:51 PM
	 */
	public static String encrypt(String input){
		if(input==null)return"";
		StringBuilder sb = new StringBuilder();
		Assert.hasText(input);
		input = Base64.getBASE64(input);
		for(int i = 0; i < input.length(); i++){
			sb.append(encrypt(input.charAt(i)));
		}
		return sb.toString();
	}
	/**
	 * 解密
	 * @author ouyang 创建时间：May 5, 2012 1:15:59 PM
	 */
	public static String decrypt(String input){
		if(input==null)return"";
		StringBuilder sb = new StringBuilder();
		Assert.hasText(input);
		for(int i = 0; i < input.length(); i++){
			sb.append(decrypt(input.charAt(i)));
		}
		return Base64.getFromBASE64(sb.toString());
	}
	

}
